package com.atguigu.srb.oss.controller.api;

import com.atguigu.aliyun.oss.service.FileService;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@Api("阿里云文件管理")
//@CrossOrigin
@RequestMapping("/api/oss/file")
public class ApiFileController {
    private final FileService fileService;

    public ApiFileController(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public R upload(@ApiParam(value = "文件", required = true) @RequestPart("file") MultipartFile file,
                    @ApiParam(value = "模块", required = true) @RequestParam("module") String module) {
        try {
            String url = fileService.upload(file.getInputStream(), module, file.getOriginalFilename());
            return R.ok().message("文件上传成功").data("url", url);
        } catch (IOException e) {
            throw new BusinessException(e, ResponseEnum.UPLOAD_ERROR);
        }
    }

    @DeleteMapping("/remove")
    @ApiOperation("文件删除")
    public R remove(@ApiParam(value = "要删除的文件", required = true) @RequestParam("url") String url) {
        fileService.removeFile(url);
        return R.ok().message("文件删除成功");
    }
}
